#!/bin/bash
#
# Post push hook for Docker Automated Build.
#
# This hook adds tags that includes the image version.

set -e # Exit immediately if a command exits with a non-zero status.
set -u # Treat unset variables as an error.

# Load mandatory environment variables.
source hooks/load_vars

echo "$(basename "$0") hook environment variables:"
( set -o posix ; set | sort | sed 's/^/    /')

# For normal versions without a beta/rc suffix, we need to add 3 tags.  For
# example, for an image version of 2.1.5:
#   - ${BASEIMAGE_DOCKER_TAG}-v2.1.5 (exact version)
#   - ${BASEIMAGE_DOCKER_TAG}-v2.1   (latest minor version)
#   - ${BASEIMAGE_DOCKER_TAG}-v2     (latest major version)

DOCKER_NEWTAG_EXACT="${BASEIMAGE_DOCKER_TAG}-v${BASEIMAGE_DOCKER_IMAGE_VERSION}"
DOCKER_NEWTAG_LATEST_MINOR=UNSET
DOCKER_NEWTAG_LATEST_MAJOR=UNSET

if [[ "$BASEIMAGE_DOCKER_IMAGE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    MAJOR="$(echo "$BASEIMAGE_DOCKER_IMAGE_VERSION" | cut -d'.' -f1)"
    MINOR="$(echo "$BASEIMAGE_DOCKER_IMAGE_VERSION" | cut -d'.' -f2)"

    DOCKER_NEWTAG_LATEST_MINOR="${BASEIMAGE_DOCKER_TAG}-v${MAJOR}.${MINOR}"
    DOCKER_NEWTAG_LATEST_MAJOR="${BASEIMAGE_DOCKER_TAG}-v${MAJOR}"
fi

for TAG in "$DOCKER_NEWTAG_EXACT" "$DOCKER_NEWTAG_LATEST_MINOR" "$DOCKER_NEWTAG_LATEST_MAJOR"
do
    [ "$TAG" != "UNSET" ] || continue
    echo "Adding tag '$TAG' to image..."
    docker tag $BASEIMAGE_DOCKER_IMAGE_NAME ${BASEIMAGE_DOCKER_REPO}:$TAG
    echo "Pushing image..."
    docker push ${BASEIMAGE_DOCKER_REPO}:$TAG
done

echo "$(basename "$0") hook terminated successfully."
